package com.cmall.common.foundation.entity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;

public class HttpClientEntity {
    private Long port = 80L;
    private String url = "";
    private TreeMap<String, Object> params = new TreeMap<String, Object>();
    private Map<String, String> header = new HashMap<String, String>();

    public HttpClientEntity() {
    }

    public HttpClientEntity(Map<String, String> param) {
    	Iterator iterator = param.entrySet().iterator();
        while(iterator.hasNext()) {
            Entry<String, Object> paramMap = (Entry)iterator.next();
            if (paramMap.getValue() instanceof String) {
            	 this.addParam(paramMap.getKey(), String.valueOf(paramMap.getValue()));
            }
        }

	}

	public StringBuffer getRequestUrl() throws Exception {
        StringBuffer requestUrl = new StringBuffer();
        if (StringUtils.isNotBlank(this.url)) {
            if (this.port != 80L) {
                requestUrl.append(this.url).append(":").append(this.port);
            } else {
                requestUrl.append(this.url);
            }

            return requestUrl;
        } else {
            throw new RuntimeException("request url is empty!");
        }
    }

    public StringBuffer getPostUrl() throws Exception {
        return this.getRequestUrl();
    }

    public StringBuffer getPutUrl() throws Exception {
        return this.getRequestUrl();
    }

    public StringBuffer getGetUrl() throws Exception {
        StringBuffer requestUrl = this.getRequestUrl();
        if (this.params.size() > 0) {
            requestUrl.append("?");
        }

        int i = 0;
        Iterator var3 = this.params.entrySet().iterator();

        while(var3.hasNext()) {
            Entry<String, Object> entry = (Entry)var3.next();
            if (entry.getValue() instanceof String) {
                if (i != 0) {
                    requestUrl.append("&");
                }

                requestUrl.append((String)entry.getKey()).append("=").append(entry.getValue().toString());
                ++i;
            }
        }

        return requestUrl;
    }

    public void clearParmas() {
        this.params.clear();
    }

    public void addParam(String name, Object value) {
        this.params.put(name, value);
    }

    public void addHeader(String name, String value) {
        this.header.put(name, value);
    }

    public void setPort(Long port) {
        this.port = port;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public TreeMap<String, Object> getParams() {
        return this.params;
    }

    public Map<String, String> getHeader() {
        return this.header;
    }
}
